package com.ang.juc.n2;

import lombok.extern.slf4j.Slf4j;

import java.util.stream.IntStream;

/**
 * 2个线程互相等待对方的锁
 */
@Slf4j
public class DeadLockTest {

    //2把锁
    public String lockA = "lockA";
    public String lockB = "lockB";

    //2个线程
    public static void main(String[] args) throws InterruptedException {
        DeadLockTest deadLockTest = new DeadLockTest();

        //先上锁A，后上锁B
        new Thread(()->{
            deadLockTest.test(deadLockTest.lockA, deadLockTest.lockB);
        },"thread1").start();

        Thread.sleep(1000);

        //先上锁，后上锁A
        new Thread(()->{
            deadLockTest.test(deadLockTest.lockB, deadLockTest.lockA);
        },"thread2").start();
    }

    //一个共享方法，注意：锁要外部传进来，因为要保证使用的锁顺序不一样
    public void test(String lock1, String lock2){
        synchronized (lock1){
            log.debug("第1层::::::线程：{}持有锁{}，",Thread.currentThread().getName(), lock1);
            synchronized (lock2){
                log.debug("第2层::::::线程：{}持有锁{}，",Thread.currentThread().getName(), lock2);
            }
        }
    }
}
